package com.tianzj.boot.mvc.service.log.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.tianzj.boot.mvc.entity.log.SysLog;
import com.tianzj.boot.mvc.repository.log.SysLogRepository;
import com.tianzj.boot.mvc.service.log.SysLogService;

@Service
public class SysLogServiceImpl implements SysLogService {

	@Autowired
	private SysLogRepository  sysLogRepository;
	
	@Override
	public void saveLog(SysLog sysLog) {
		sysLogRepository.save(sysLog);
	}

	@Override
	public Page<SysLog> getSysLogList(final SysLog sysLog, Pageable pageable) {
		Specification<SysLog> specification = new Specification<SysLog>() {  
            @Override  
            public Predicate toPredicate(Root<SysLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {  
                Path<String> username = root.get("username");  
                Path<Long> useTime = root.get("useTime");  
                Predicate predicate = null;
                if(StringUtils.isNotBlank(sysLog.getUsername())){
                	  predicate =cb.and(cb.like(username, "%"+sysLog.getUsername()+"%"));
                }
                if(sysLog.getStartTime()!=null&&sysLog.getEndTime()!=null){
                	Predicate predicate2=cb.and(cb.between(useTime, sysLog.getStartTime(), sysLog.getEndTime()));
                	 predicate = getPre(cb, predicate, predicate2);
                }
                return predicate;  
            }
		 
        };  
        Page<SysLog> sysLogs = sysLogRepository.findAll(specification,pageable);
		return sysLogs;
	}
	
	private Predicate getPre(CriteriaBuilder cb, Predicate predicate, Predicate predicate2) {
		if(predicate!=null){
			 predicate=cb.and(predicate, predicate2);
		 }else{
			 predicate=predicate2;
		 }
		return predicate;
	}

	@Override
	public SysLog getLogById(Long id) {
		return sysLogRepository.findOne(id);
	}

}
